import { ref, computed, onMounted } from 'vue'
import { defineStore } from 'pinia'

export const useShoppingCarStore = defineStore('shoppingCar', () => {
   const shoppingCar = ref([])
   const totalPrice = computed(() => {
      let sum = 0
      shoppingCar.value.forEach(item => {
         sum += item.price * item.number
      })
      return sum
   })
   const addItem = (product) => {
      const item= {}
      item.id = product.id
      const index = shoppingCar.value.findIndex(i => i.id === item.id)
      if (index > -1) {
         shoppingCar.value[index].number += 1
      } else {
         item.title = product.title
         item.price = product.price
         item.number = 1
         shoppingCar.value.push(item)
      }
   }
   const removeItem = (item) => {
      const index = shoppingCar.value.indexOf(item)
      if (index > -1) {
         shoppingCar.value.splice(index, 1)
      }
   }
   const clear = () => {
      shoppingCar.value = []
   }
   return {
      shoppingCar,
      totalPrice,
      addItem,
      removeItem,
      clear
   }
})
